# -*_ codeing=utf-8 -*-
# @Time: 2025/10/29 14:28
# @Author: foxhuty
# @File: views.py
# @Software: PyCharm
# @Based on python 3.13
from email.policy import default
from typing import List

from fastapi import APIRouter, Depends, HTTPException, Query, Path, Body
from sqlalchemy import select, update, delete
from sqlalchemy.orm import Session
from pydantic_notes.schemas import EmployeeCreateSchema, EmpResponse
from sqlalchemy_notes.db_main import get_session
from sqlalchemy_notes.student_manager.models import Student

emp_notes = APIRouter(prefix="/notes", tags=["员工的增删改查的案例"])


@emp_notes.post(path="/emp/", description='新增一个员工', response_model=EmployeeCreateSchema)
async def create_employee(emp: EmployeeCreateSchema, session: Session = Depends(get_session)):
    # 判断员工的名字是否重复
    db_emp = session.execute(select(Student).where(Student.name == emp.name)).first()
    if db_emp:
        raise HTTPException(status_code=405, detail="Employee already exists")
    # 把emp(pydantic模型对象)转换成ORM的模型对象(Student)
    db_emp = Student(**emp.model_dump())
    session.add(db_emp)
    session.commit()
    return db_emp


# 查询员工信息，包括部门信息
@emp_notes.post(path="/emp/{emp_id}", description='查询一个员工', response_model=EmpResponse)
async def query_employee(emp_id: int, session: Session = Depends(get_session)):
    db_emp = session.get(Student, emp_id)
    if db_emp:
        return db_emp
    else:
        raise HTTPException(status_code=405, detail=f"ID为{emp_id}，没有查到相应员工数据")


# 分布查询所有员工信息，包括部门信息
@emp_notes.post(path="/emp_list/", description='查询所有员工列表', response_model=List[EmpResponse])
async def query_employee_list(offset: int = Query(default=0, description='起始下标'),
                              page_size: int = Query(default=5),
                              session: Session = Depends(get_session)):
    return session.scalars(select(Student).offset(offset).limit(page_size)).all()


@emp_notes.put(path="/emp_update/{emp_id}", description='修改员工信息', response_model=EmpResponse)
async def employee_update(emp_id: int = Path(description='要修改的员工id'),
                          emp: EmployeeCreateSchema = Body(description='要修改的员工信息'),
                          session: Session = Depends(get_session)):
    emp.id = emp_id
    session.execute(update(Student), [emp.model_dump(exclude_unset=True)])
    db_emp = session.get(Student, emp_id)
    session.commit()
    return db_emp


@emp_notes.delete(path="/emp_delete/{emp_id}", description='修改员工信息')
async def employee_delete(emp_id: int = Path(description='要删除的员工id'), session: Session = Depends(get_session)):
    session.execute(delete(Student).where(Student.id == emp_id))
    session.commit()
    return {'detail': 'successfully deleted'}
